<template>
  <t-dialog v-model:visible="model" :header="dialogTitle" :confirm-loading="confirmPending" confirm-btn="确定" @confirm="handleConfirm">
    <t-form ref="dialogForm" :data="formData" :rules="rules">
      <t-form-item label="用户名" name="userName">
        <t-input v-model="formData.userName" placeholder="请输入用户名" />
      </t-form-item>
      <t-form-item label="角色" name="userRole">
        <t-select v-model="formData.userRole" placeholder="请选择角色">
          <t-option v-for="item in UserRole" :key="item" :label="userRoleDict[item]" :value="item" />
        </t-select>
      </t-form-item>
      <t-form-item v-if="isCompanyUser(formData)" label="渠道" name="companyId">
        <t-select v-model="formData.companyId" placeholder="请选择渠道" filterable :options="companyOptions" :loading="companySearchPending" @search="handleCompanySearch" />
      </t-form-item>
      <t-form-item label="密码" name="password">
        <t-input v-model="formData.password" placeholder="请输入密码" type="password" autocomplete="new-password" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import type { FormInstanceFunctions, FormRules } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { computed, reactive, ref, useTemplateRef } from 'vue'

import { getChannelDetail, getChannelPageList } from '@/api/channel'
import type { SysCompanyUserReqData, UserReqData } from '@/api/model/user'
import { UserRole } from '@/api/model/user'
import { createUser, updateUser } from '@/api/user'
import useSearchSelect from '@/hooks/selectSearch'
import { userRoleDict } from '@/utils/dict/user'

export type UserFormDialogData = UserReqData
const props = defineProps<{ id?: string, data: UserFormDialogData }>()
const emits = defineEmits<{
  (e: 'success'): void
}>()
const model = defineModel('visible', {
  type: Boolean,
})
const isEditMode = computed(() => !!props.id)
const dialogTitle = computed(() => (isEditMode.value ? '编辑用户' : '添加用户'))
function isCompanyUser(user: UserReqData): user is SysCompanyUserReqData {
  return user.userRole === UserRole.COMPANY_ADMIN || user.userRole === UserRole.GUIDE
}

const formData = reactive<UserFormDialogData>(props.data)
const rules: FormRules<UserFormDialogData> = {
  userName: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }],
  userRole: [{ required: true, message: '请选择角色' }],
  companyId: [{ required: true, message: '请选择渠道' }],
}
const dialogForm = useTemplateRef<FormInstanceFunctions<UserFormDialogData>>('dialogForm')

const { selectOptions: companyOptions, searchLoading: companySearchPending, handleSearch: handleCompanySearch } = useSearchSelect(() => isCompanyUser(formData) ? formData.companyId : '', async (companyId) => {
  const channelDetail = await getChannelDetail(companyId)
  return {
    label: channelDetail.companyName,
    value: channelDetail.id,
  }
}, async (_companyNameKey) => {
  const channelList = await getChannelPageList()
  return channelList.data.map(item => ({ label: item.companyName, value: item.id }))
})
const confirmPending = ref(false)
function handleConfirm() {
  dialogForm.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      confirmPending.value = true
      if (isEditMode.value) {
        updateUser({ id: props.id!, ...formData }).then(() => {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('更新成功')
          emits('success')
        })
      }
      else {
        createUser(formData).then(() => {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('创建成功')
          emits('success')
        })
      }
    }
  })
}
</script>
<style scoped>

</style>
